package com.wanyangproject.fuwuactivity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.wanyangproject.R;
import com.wanyangproject.entity.PhotoEntity;
import com.wanyangproject.entity.QiYeShenQingShiBaiEntity;
import com.wanyangproject.entity.UserEntity;
import com.wanyangproject.popuwindow.EndPopupWindow;
import com.wanyangproject.popuwindow.StartPopupWindow;
import com.wanyangproject.popuwindow.TakePhotoPopWin;
import com.wanyangproject.utils.ContractUtils;
import com.wanyangproject.utils.GlideImageLoaderForPicker;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

//  企业申请服务
public class QiYeShenQingFuWuActivity extends AppCompatActivity {

    @BindView(R.id.image_back)
    ImageView imageBack;
    @BindView(R.id.et_beizhu)
    EditText etBeizhu;
    @BindView(R.id.tv_liji_shenqing)
    TextView tvLijiShenqing;
    @BindView(R.id.et_number)
    EditText etNumber;
    @BindView(R.id.et_youhuiquan_jine)
    EditText etYouhuiquanJine;
    @BindView(R.id.image_shi)
    ImageView imageShi;
    @BindView(R.id.image_fou)
    ImageView imageFou;
    @BindView(R.id.tv_shenqing_fuwu)
    TextView tvShenqingFuwu;
    @BindView(R.id.tv_jianjie)
    TextView tvJianjie;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_youxiaoqi)
    TextView tvYouxiaoqi;
    @BindView(R.id.tv_start)
    TextView tvStart;
    @BindView(R.id.tv_dao)
    TextView tvDao;
    @BindView(R.id.tv_end)
    TextView tvEnd;
    @BindView(R.id.image_add_one)
    ImageView imageAddOne;
    @BindView(R.id.image_delete_one)
    ImageView imageDeleteOne;
    @BindView(R.id.image_add_two)
    ImageView imageAddTwo;
    @BindView(R.id.image_delete_two)
    ImageView imageDeleteTwo;
    @BindView(R.id.image_add_three)
    ImageView imageAddThree;
    @BindView(R.id.image_delete_three)
    ImageView imageDeleteThree;
    @BindView(R.id.relative_time)
    RelativeLayout relativeTime;
    private StartPopupWindow startPopupWindow;
    private EndPopupWindow endPopupWindow;
    private String fuwuid;
    private String title;
    private String jianjie;
    private String yongjiu = "2";
    private UserEntity userEntity;
    private String startstring = "";//时间戳
    private String endstring = "";//时间戳
    private SimpleDateFormat simpleDateFormat;
    private SimpleDateFormat simpleDateFormat1;
    private long timestart;
    private long timeend;
    private int ISOK = 0;
    private TakePhotoPopWin takePhotoPopWin;
    //    private ArrayList<ImageItem> list = new ArrayList<>();// 图片
    private ArrayList<String> list1 = new ArrayList<>();// 图片
    private ArrayList<ImageView> add = new ArrayList(); //  带加号的原图
    private ArrayList<String> imageUrl = new ArrayList<>(); // 图片网址
    private ArrayList<ImageView> shanchu = new ArrayList<>();// 删除的按钮
    private PhotoEntity photoEntity;
    private Uri photoUri;
    private String neirong;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qi_ye_shen_qing_fu_wu);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= 21) {
            View dview = getWindow().getDecorView();
            dview.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }

        Intent intent = getIntent();
        fuwuid = intent.getStringExtra("id");
        neirong = intent.getStringExtra("neirong");
        title = intent.getStringExtra("title");

//        title = intent.getStringExtra("title");
//        jianjie = intent.getStringExtra("jianjie");
//        System.out.println(title + "    接收的标题");
//        System.out.println(jianjie + "    接收的简介");
        System.out.println(fuwuid + "      企业申请接收的id");

        tvShenqingFuwu.setText(title);
        tvJianjie.setText(neirong);


        add.add(imageAddOne);
        add.add(imageAddTwo);
        add.add(imageAddThree);

        shanchu.add(imageDeleteOne);
        shanchu.add(imageDeleteTwo);
        shanchu.add(imageDeleteThree);


//        获取用户信息的网络请求
        initYongHuXinXiHttp();
    }


    //    获取用户信息的网络请求
    private void initYongHuXinXiHttp() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "Life/user")
                .addHeader("token", ContractUtils.getTOKEN(QiYeShenQingFuWuActivity.this))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ContractUtils.Code500(QiYeShenQingFuWuActivity.this, response);
                        System.out.println(response + "    获取个人用户信息的网络请求");
                        Gson gson = new Gson();
                        userEntity = gson.fromJson(response, UserEntity.class);
                        if(response.indexOf("200") != -1){
//                            etName.setText(userEntity.getResponse().getNickname());//昵称
                            etName.setText(userEntity.getResponse().getRealname());//真实姓名
                            etPhone.setText(userEntity.getResponse().getUsername());
                        }
                    }
                });
    }

    @OnClick({R.id.image_back, R.id.tv_start, R.id.image_add_one, R.id.image_delete_one, R.id.image_add_two, R.id.image_delete_two, R.id.image_add_three, R.id.image_delete_three, R.id.tv_shenqing_fuwu, R.id.tv_jianjie, R.id.tv_end, R.id.et_beizhu, R.id.tv_liji_shenqing, R.id.et_number, R.id.et_youhuiquan_jine, R.id.image_shi, R.id.image_fou})
    public void onViewClicked(View view) {
        switch (view.getId()) {
//            返回按钮
            case R.id.image_back:
                finish();
                break;
            case R.id.et_number:
                break;
            case R.id.et_youhuiquan_jine:
                break;
//            申请服务
            case R.id.tv_shenqing_fuwu:
                break;
//            简介
            case R.id.tv_jianjie:
                break;
            case R.id.image_shi:
                imageShi.setImageResource(R.drawable.checked);
                imageFou.setImageResource(R.drawable.unchecked);
                yongjiu = "2";
                relativeTime.setVisibility(View.GONE);

//                tvYouxiaoqi.setVisibility(View.GONE);
//                tvDao.setVisibility(View.GONE);
//                tvStart.setVisibility(View.GONE);
//                tvEnd.setVisibility(View.GONE);
                break;
            case R.id.image_fou:
                imageFou.setImageResource(R.drawable.checked);
                imageShi.setImageResource(R.drawable.unchecked);
                yongjiu = "1";
                relativeTime.setVisibility(View.VISIBLE);
//                tvYouxiaoqi.setVisibility(View.VISIBLE);
//                tvDao.setVisibility(View.VISIBLE);
//                tvStart.setVisibility(View.VISIBLE);
//                tvEnd.setVisibility(View.VISIBLE);
                break;
//            开始时间
            case R.id.tv_start:
                    TimePickerView timePickerView = new TimePickerView.Builder(QiYeShenQingFuWuActivity.this, new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            tvStart.setText(simpleDateFormat.format(date));
                            System.out.println(tvStart.getText().toString().trim()+"      开始时间");
//                        try {
//                            Date date1 = simpleDateFormat1.parse(tvStart.getText().toString());
//                            long timestart = date1.getTime();
////                            startstring = String.valueOf(time);
////                            System.out.println(startstring + "     时间戳");
//                        } catch (ParseException e) {
//                            e.printStackTrace();
//                        }
                        }
                    })
                            .setType(new boolean[]{true, true, true, false, false, false})//默认全部显示
                            .setCancelText("取消")//取消按钮文字
                            .setSubmitText("确定")//确认按钮文字
                            .setTextXOffset(0, 0, 0, 0, 0, 0)
                            .setLunarCalendar(false)
//                        .setContentSize(20)//滚轮文字大小
                            .gravity(Gravity.CENTER)
                            .setTitleSize(16)//标题文字大小
//                        .setLineSpacingMultiplier(3.0f)//设置两横线之间的间隔倍数
                            .setTitleText("开始日期")//标题文字
                            .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                            .isCyclic(true)//是否循环滚动
                            .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                            .setTextColorOut(Color.parseColor("#AEAAAA"))
                            .setTitleColor(Color.BLACK)//标题文字颜色
                            .setSubmitColor(Color.RED)//确定按钮文字颜色
                            .setCancelColor(Color.parseColor("#AEAAAA"))//取消按钮文字颜色
                            .setTitleBgColor(Color.parseColor("#f5f5f5"))//标题背景颜色 Night mode
                            .setBgColor(Color.parseColor("#ffffff"))//滚轮背景颜色 Night mode
//                        .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
//                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
//                        .setRangDate(startDate,endDate)//起始终止年月日设定
                            .setLabel("年", "月", "日", ":", "", "")
                            .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                            .isDialog(false)//是否显示为对话框样式
                            .build();
                    timePickerView.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                    timePickerView.show();


                break;
//            结束时间
            case R.id.tv_end:
                    TimePickerView timePickerView1 = new TimePickerView.Builder(QiYeShenQingFuWuActivity.this, new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
                            tvEnd.setText(simpleDateFormat1.format(date));
                            System.out.println(tvEnd.getText().toString().trim()+"      结束时间");
//                        try {
//                            Date date1 = simpleDateFormat1.parse(tvEnd.getText().toString());
//                            long timeend = date1.getTime();
////                            endstring = String.valueOf(time);
////                            System.out.println(endstring + "     时间戳");
//                        } catch (ParseException e) {
//                            e.printStackTrace();
//                        }
                        }
                    })
                            .setType(new boolean[]{true, true, true, false, false, false})//默认全部显示
                            .setCancelText("取消")//取消按钮文字
                            .setSubmitText("确定")//确认按钮文字
                            .setTextXOffset(0, 0, 0, 0, 0, 0)
                            .setLunarCalendar(false)
//                        .setContentSize(20)//滚轮文字大小
                            .gravity(Gravity.CENTER)
                            .setTitleSize(16)//标题文字大小
//                        .setLineSpacingMultiplier(3.0f)//设置两横线之间的间隔倍数
                            .setTitleText("结束日期")//标题文字
                            .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                            .isCyclic(true)//是否循环滚动
                            .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                            .setTextColorOut(Color.parseColor("#AEAAAA"))
                            .setTitleColor(Color.BLACK)//标题文字颜色
                            .setSubmitColor(Color.RED)//确定按钮文字颜色
                            .setCancelColor(Color.parseColor("#AEAAAA"))//取消按钮文字颜色
                            .setTitleBgColor(Color.parseColor("#f5f5f5"))//标题背景颜色 Night mode
                            .setBgColor(Color.parseColor("#ffffff"))//滚轮背景颜色 Night mode
//                        .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
//                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
//                        .setRangDate(startDate,endDate)//起始终止年月日设定
                            .setLabel("年", "月", "日", ":", "", "")
                            .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                            .isDialog(false)//是否显示为对话框样式
                            .build();
                    timePickerView1.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                    timePickerView1.show();
                break;
//            备注
            case R.id.et_beizhu:
                break;
//            立即申请
            case R.id.tv_liji_shenqing:



                Calendar instance = Calendar.getInstance();

                int year = instance.get(Calendar.YEAR);
                int month = instance.get(Calendar.MONTH)+1;// 获取当前月份
                int day = instance.get(Calendar.DAY_OF_MONTH);// 获取当日期
//                int hour = instance.get(Calendar.HOUR_OF_DAY);
//                int minute = instance.get(Calendar.MINUTE);
                System.out.println(month+"      month");
                System.out.println(day+"      day");
//                System.out.println(hour+"       hour");
//                System.out.println(minute+"         minute");
                System.out.println(tvStart.getText().toString().trim()+"         tvStart");


                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date date = sdf.parse(tvStart.getText().toString().trim());
                    System.out.println(date+"    date");
                    System.out.println(date.getTime()+"            date.getTime()");
                    Date date1 = sdf.parse(year+"-"+month+"-"+day);
                    System.out.println(year+"-"+month+"-"+day+"         开始时间");

                    if(date.getTime() < date1.getTime()){
                        Toast.makeText(this, "请输入正确的开始时间！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }




                if (tvStart.getText().toString().trim().equals("") || tvEnd.getText().toString().trim().equals("")) {

                } else {

                    try {
                        Date date = simpleDateFormat.parse(tvStart.getText().toString());
                        timestart = date.getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }


                    try {
                        Date date1 = simpleDateFormat1.parse(tvEnd.getText().toString());
                        timeend = date1.getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }


                    if (timestart > timeend) {
                        Toast.makeText(this, "开始时间应该小于结束时间", Toast.LENGTH_SHORT).show();
                        return;
                    }

                }


                if (etPhone.getText().toString().trim().equals("")) {

                } else {
                    if (ContractUtils.isChinaPhoneLegal(etPhone.getText().toString().trim()) == false) {
                        Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

//                ContractUtils.isChinaPhoneLegal(etPhone.getText().toString().trim());


//                if (yongjiu.equals("")) {
//                    Toast.makeText(this, "请选择是否永久使用", Toast.LENGTH_SHORT).show();
//                } else
                if(yongjiu.equals("1")){
                    if (tvStart.getText().toString().trim().equals("")) {
                        Toast.makeText(this, "请输入开始时间", Toast.LENGTH_SHORT).show();
                        return;
                    } else if (tvEnd.getText().toString().equals("")) {
                        Toast.makeText(this, "请输入结束时间", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                if (etNumber.getText().toString().trim().equals("")) {
                    Toast.makeText(this, "请输入数量", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (etYouhuiquanJine.getText().toString().trim().equals("")) {
                    Toast.makeText(this, "请输入金额", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (etName.getText().toString().trim().equals("")) {
                    Toast.makeText(this, "请输入申请人姓名", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (etPhone.getText().toString().trim().equals("")) {
                    Toast.makeText(this, "请输入申请人电话", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(etBeizhu.getText().toString().trim().equals("")){
                    Toast.makeText(this, "请输入备注", Toast.LENGTH_SHORT).show();
                    return;
                }

                {
//                    //                申请物业服务的网络请求
//                    initShenQingWuYeFuWuHTTP();

                    if (list1.size() == 0) {
//                        没有图片的
                        //                申请物业服务的网络请求
                        initShenQingWuYeFuWuHTTP();
                    }
                    for (int i = 0; i < list1.size(); i++) {
                        uploadFile(list1.get(i));
                    }


                }
                break;
            //            第一张图片加号
            case R.id.image_add_one:
                ISOK = 0;
                //                弹出上传图片的弹窗
                initTanChu();
                break;
//            第二张图加号
            case R.id.image_add_two:
                ISOK = 1;
                //                弹出上传图片的弹窗
                initTanChu();
                break;
//            第三张图片加号
            case R.id.image_add_three:
                ISOK = 2;
                //                弹出上传图片的弹窗
                initTanChu();
                break;
//            第一个删除按钮
            case R.id.image_delete_one:
                list1.remove(0);
                TuPian();
                break;
//            第二个删除按钮
            case R.id.image_delete_two:
                list1.remove(1);
                TuPian();
                break;
//            第三个删除按钮
            case R.id.image_delete_three:
                list1.remove(2);
                TuPian();
                break;
////            申请人姓名
//            case R.id.tv_name:
//                break;
////            申请人电话
//            case R.id.tv_phone:
//                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

//        相机回调
        if (requestCode == 100) {
            String string = photoUri.toString();
            File file = new File(string);
            System.out.println(file.exists()+"      file");
            if(file.exists() == false){
                return;
            }

            if (list1.size() - 1 >= ISOK) {
                list1.set(ISOK, string);
            } else {
                list1.add(string);
            }
            TuPian();

        }
//        String string = photoUri.toString();
//        imageTouxiang.setImageURI(Uri.parse(string));
//        uploadFile1(string);


//        相册回调
        if (data != null && requestCode == 1) {
            ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            if (images != null) {
                if (list1.size() - 1 >= ISOK) {
                    list1.set(ISOK, images.get(0).path);
                } else {
                    list1.add(images.get(0).path);
                }
                TuPian();
            } else {
                Toast.makeText(this, "图片解析失败", Toast.LENGTH_SHORT).show();
            }


//            if (images != null) {
//                if (list.size() - 1 >= ISOK) {
//                    list.set(ISOK, images.get(0));
//                } else {
//                    list.add(images.get(0));
//                }
//                TuPian();
//            } else {
//                Toast.makeText(this, "图片解析失败", Toast.LENGTH_SHORT).show();
//            }
        }
//        else {
//            Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
//        }
    }


    private void uploadFile(String imageItem) {
        final ProgressDialog progressDialog = new ProgressDialog(QiYeShenQingFuWuActivity.this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("请等待...");
        progressDialog.setCancelable(false);
        progressDialog.show();
        File file = new File(imageItem);
        Luban.with(this)
                .load(file)
                .ignoreBy(100)
                //  .setTargetDir(AppConfig.DEFAULT_SAVE_IMAGE_PATH)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
                        OkHttpClient okHttpClient = new OkHttpClient();
                        RequestBody requestBody = new MultipartBody.Builder()
                                .setType(MultipartBody.FORM)
                                .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file))
                                .build();
                        Request request = new Request.Builder()
                                .url(ContractUtils.LOGIN_URL + "index/upload")
                                .post(requestBody)
                                .addHeader("token", ContractUtils.getTOKEN(QiYeShenQingFuWuActivity.this))
                                .build();
                        okHttpClient.newCall(request).enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
//                                        Toast.makeText(QiYeShenQingFuWuActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                                    }
                                });
                                progressDialog.dismiss();

                            }

                            @Override
                            public void onResponse(Call call, final Response response) throws IOException {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(QiYeShenQingFuWuActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                                    }
                                });


                                progressDialog.dismiss();
                                String string = response.body().string();
                                Gson gson = new Gson();
                                photoEntity = gson.fromJson(string, PhotoEntity.class);
                                imageUrl.add(photoEntity.getResponse().getFileurl());
                                if (imageUrl.size() == list1.size()) {
//                                      有图片的
//                                  申请物业服务的网络请求
                                    initQiYeFuWuLiJiShenQingTuPianHttp();
                                }
                                System.out.println(string + "   发帖上传图片");
                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();
    }


    //    //                                      有图片的
//                                  申请物业服务的网络请求
    private void initQiYeFuWuLiJiShenQingTuPianHttp() {
        System.out.println(yongjiu + "      永久");
//        System.out.println(tvStart.getText().toString().trim() + " - " + tvEnd.getText().toString().trim() + "   shijian");

        if (ContractUtils.isChinaPhoneLegal(etPhone.getText().toString().trim()) == false) {
            Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        ContractUtils.isChinaPhoneLegal(etPhone.getText().toString().trim());


        String url = "";
        for (int i = 0; i < imageUrl.size(); i++) {
            url = url + imageUrl.get(i) + ",";
        }
        url = url.substring(0, url.length() - 1);


        if (yongjiu.equals("2")) {// 1 有效期   2 永久
            OkHttpUtils.post()
                    .url(ContractUtils.LOGIN_URL + "Life/service")
                    .addHeader("token", ContractUtils.getTOKEN(QiYeShenQingFuWuActivity.this))
                    .addParams("parkId", ContractUtils.getParkId(QiYeShenQingFuWuActivity.this))
                    .addParams("Preferences_id", fuwuid)
                    .addParams("money", etYouhuiquanJine.getText().toString().trim())
                    .addParams("nember", etNumber.getText().toString().trim())
                    .addParams("permanent", yongjiu)
                    .addParams("Remarks", etBeizhu.getText().toString().trim())
                    .addParams("name", etName.getText().toString().trim())
                    .addParams("phone", etPhone.getText().toString().trim())
                    .addParams("photo", url)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            System.out.println(e + "     111eeeeeee");
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            System.out.println(ContractUtils.getTOKEN(QiYeShenQingFuWuActivity.this) + "       token");
                            System.out.println(ContractUtils.getParkId(QiYeShenQingFuWuActivity.this) + "      parkId");
                            System.out.println(fuwuid + "        Preferences_id ");
                            System.out.println(etYouhuiquanJine.getText().toString().trim() + "          money");
                            System.out.println(etNumber.getText().toString().trim() + "            nember ");
                            System.out.println(yongjiu + "           permanent");
                            System.out.println(etBeizhu.getText().toString().trim() + "         Remarks ");
                            System.out.println(etName.getText().toString().trim() + "      name  ");
                            System.out.println(etPhone.getText().toString().trim() + "         phone");

                            ContractUtils.Code500(QiYeShenQingFuWuActivity.this, response);
                            System.out.println(response + "       申请物业服务的网络请求");
                            if (response.indexOf("200") != -1) {
//                                Gson gson = new Gson();
//                                QiYeFuWuShenQingEntity qiYeFuWuShenQingEntity = gson.fromJson(response, QiYeFuWuShenQingEntity.class);
                                Toast.makeText(QiYeShenQingFuWuActivity.this, "申请成功！", Toast.LENGTH_SHORT).show();
//                                Intent intent = new Intent(QiYeShenQingFuWuActivity.this,FuWuShenQingJiLuJinXingActivity.class);
//                                intent.putExtra("entype","2");
//                                startActivity(intent);
                                finish();
                            } else if (response.indexOf("400") != -1) {
                                Gson gson = new Gson();
                                QiYeShenQingShiBaiEntity qiYeShenQingShiBaiEntity = gson.fromJson(response, QiYeShenQingShiBaiEntity.class);
                                Toast.makeText(QiYeShenQingFuWuActivity.this, qiYeShenQingShiBaiEntity.getMsg(), Toast.LENGTH_SHORT).show();
                                finish();
                            }

                        }
                    });
        } else if (yongjiu.equals("1")) {
            OkHttpUtils.post()
                    .url(ContractUtils.LOGIN_URL + "Life/service")
                    .addHeader("token", ContractUtils.getTOKEN(QiYeShenQingFuWuActivity.this))
                    .addParams("parkId", ContractUtils.getParkId(QiYeShenQingFuWuActivity.this))
                    .addParams("Preferences_id", fuwuid)
                    .addParams("money", etYouhuiquanJine.getText().toString().trim())
                    .addParams("nember", etNumber.getText().toString().trim())
                    .addParams("permanent", yongjiu)
                    .addParams("use_time", tvStart.getText().toString().trim() + " - " + tvEnd.getText().toString().trim())
                    .addParams("Remarks", etBeizhu.getText().toString().trim())
                    .addParams("name", etName.getText().toString().trim())
                    .addParams("phone", etPhone.getText().toString().trim())
                    .addParams("photo", url)//图片的网址
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            System.out.println(e + "    222eeeeeeeeee");
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            String s = tvStart.getText().toString().trim() + " - " + tvEnd.getText().toString().trim();
                            System.out.println(s+"      sssssssss1111111111");
                            System.out.println(ContractUtils.getTOKEN(QiYeShenQingFuWuActivity.this) + "       token");
                            System.out.println(ContractUtils.getParkId(QiYeShenQingFuWuActivity.this) + "      parkId");
                            System.out.println(fuwuid + "        Preferences_id ");
                            System.out.println(etYouhuiquanJine.getText().toString().trim() + "          money");
                            System.out.println(etNumber.getText().toString().trim() + "            nember ");
                            System.out.println(yongjiu + "           permanent");
                            System.out.println(etBeizhu.getText().toString().trim() + "         Remarks ");
                            System.out.println(etName.getText().toString().trim() + "      name  ");
                            System.out.println(etPhone.getText().toString().trim() + "         phone");
                            System.out.println(tvStart.getText().toString().trim() + " - " + tvEnd.getText().toString().trim() + "         use_time ");


                            ContractUtils.Code500(QiYeShenQingFuWuActivity.this, response);
                            System.out.println(response + "       申请物业服务的网络请求");
                            if (response.indexOf("200") != -1) {
//                                Gson gson = new Gson();
//                                QiYeFuWuShenQingEntity qiYeFuWuShenQingEntity = gson.fromJson(response, QiYeFuWuShenQingEntity.class);
                                Toast.makeText(QiYeShenQingFuWuActivity.this, "申请成功！", Toast.LENGTH_SHORT).show();
//                                Intent intent = new Intent(QiYeShenQingFuWuActivity.this,FuWuShenQingJiLuJinXingActivity.class);
//                                intent.putExtra("entype","2");
//                                startActivity(intent);
                                finish();
                            } else if (response.indexOf("400") != -1) {
                                Gson gson = new Gson();
                                QiYeShenQingShiBaiEntity qiYeShenQingShiBaiEntity = gson.fromJson(response, QiYeShenQingShiBaiEntity.class);
                                Toast.makeText(QiYeShenQingFuWuActivity.this, qiYeShenQingShiBaiEntity.getMsg(), Toast.LENGTH_SHORT).show();
                                finish();
                            }


                        }
                    });
        }
    }


    //    弹出上传图片的弹窗
    private void initTanChu() {
        Object itemsOnClick = null;
        takePhotoPopWin = new TakePhotoPopWin(QiYeShenQingFuWuActivity.this, (View.OnClickListener) itemsOnClick);
        takePhotoPopWin.showAtLocation(findViewById(R.id.relative_shenqingfuwu), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);


        //        点击相机

        takePhotoPopWin.setOnClickXiangji(new TakePhotoPopWin.OnClickXiangji() {
            @Override
            public void onClick(int id) {
//                        Intent open = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                        startActivityForResult(open,100);


                //                判断当前SDK版本号
                if (Build.VERSION.SDK_INT >= 23) {
//                    当前拨打电话权限是没有给的
                    if (ContextCompat.checkSelfPermission(QiYeShenQingFuWuActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//                        我要请求权限
                        ActivityCompat.requestPermissions(QiYeShenQingFuWuActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                    } else {
                        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                            //创建文件夹 在本地文件Pictures 目录下创建 自己得文件夹
                            File dir = new File(Environment.getExternalStorageDirectory() + "/Pictures/image");
                            if (!dir.exists()) {
                                dir.mkdirs();
                            }
                            //照片名称
                            File file = new File(dir, new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg");
                            photoUri = Uri.parse(file.getPath());

                            startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                                    .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)), 100);

                        } else {
//                                    showToast("请检查SDCard！");
                        }
                    }
                } else {

                    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                        //创建文件夹 在本地文件Pictures 目录下创建 自己得文件夹
                        File dir = new File(Environment.getExternalStorageDirectory() + "/Pictures/image");
                        if (!dir.exists()) {
                            dir.mkdirs();
                        }
                        //照片名称
                        File file = new File(dir, new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg");
                        photoUri = Uri.parse(file.getPath());

                        startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                                .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)), 100);

                    } else {
//               showToast("请检查SDCard！");
                    }
                }

            }
        });


        //                点击相册
        takePhotoPopWin.setOnClickXiangce(new TakePhotoPopWin.OnClickXiangce() {
            @Override
            public void onClick(int id) {
//                        Intent local = new Intent();
//                        local.setType("image/*");
//                        local.setAction(Intent.ACTION_GET_CONTENT);
//                        startActivityForResult(local, 2);

                ImagePicker imagePicker = ImagePicker.getInstance();
                imagePicker.setImageLoader(new GlideImageLoaderForPicker());   //设置图片加载器
                imagePicker.setShowCamera(true);  //显示拍照按钮
                imagePicker.setCrop(false);        //允许裁剪（单选才有效）
                imagePicker.setSaveRectangle(true);//是否按矩形区域保存
                imagePicker.setFocusHeight(169);
                imagePicker.setFocusWidth(169);
                imagePicker.setCrop(false);
                imagePicker.setSelectLimit(1);    //选中数量限制
                imagePicker.setOutPutX(800);//保存文件的宽度。单位像素
                imagePicker.setOutPutY(800);//保存文件的高度。单位像素

                Intent intent = new Intent(QiYeShenQingFuWuActivity.this, ImageGridActivity.class);
                startActivityForResult(intent, 1);

            }
        });
    }


    //    图片显示与隐藏
    private void TuPian() {

        for (int i = 0; i < add.size(); i++) {
            ImageView delete = shanchu.get(i);
            ImageView image = add.get(i);
            if (i <= list1.size() - 1) {
                image.setImageURI(Uri.parse(list1.get(i)));
            }
            if (i <= list1.size() - 1) {
                image.setVisibility(View.VISIBLE);
                delete.setVisibility(View.VISIBLE);
            } else if (i == list1.size()) {
                image.setVisibility(View.VISIBLE);
                delete.setVisibility(View.GONE);
                image.setImageResource(R.drawable.add);
            } else {
                image.setVisibility(View.GONE);
                delete.setVisibility(View.GONE);
            }
        }
    }


    //    申请物业服务的网络请求
//    tiantian
//    parkId     Preferences_id
    private void initShenQingWuYeFuWuHTTP() { /// 1 有效期   2 永久
        System.out.println(yongjiu + "      永久");
//        System.out.println(tvStart.getText().toString().trim() + " - " + tvEnd.getText().toString().trim() + "   shijian");

        if (ContractUtils.isChinaPhoneLegal(etPhone.getText().toString().trim()) == false) {
            Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        ContractUtils.isChinaPhoneLegal(etPhone.getText().toString().trim());

        if (yongjiu.equals("2")) {
            OkHttpUtils.post()
                    .url(ContractUtils.LOGIN_URL + "Life/service")
                    .addHeader("token", ContractUtils.getTOKEN(QiYeShenQingFuWuActivity.this))
                    .addParams("parkId", ContractUtils.getParkId(QiYeShenQingFuWuActivity.this))
                    .addParams("Preferences_id", fuwuid)
                    .addParams("money", etYouhuiquanJine.getText().toString().trim())
                    .addParams("nember", etNumber.getText().toString().trim())
                    .addParams("permanent", yongjiu)
                    .addParams("Remarks", etBeizhu.getText().toString().trim())
                    .addParams("name", etName.getText().toString().trim())
                    .addParams("phone", etPhone.getText().toString().trim())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            System.out.println(e + "     111eeeeeee");
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            System.out.println(ContractUtils.getTOKEN(QiYeShenQingFuWuActivity.this) + "       token");
                            System.out.println(ContractUtils.getParkId(QiYeShenQingFuWuActivity.this) + "      parkId");
                            System.out.println(fuwuid + "        Preferences_id ");
                            System.out.println(etYouhuiquanJine.getText().toString().trim() + "          money");
                            System.out.println(etNumber.getText().toString().trim() + "            nember ");
                            System.out.println(yongjiu + "           permanent");
                            System.out.println(etBeizhu.getText().toString().trim() + "         Remarks ");
                            System.out.println(etName.getText().toString().trim() + "      name  ");
                            System.out.println(etPhone.getText().toString().trim() + "         phone");

                            ContractUtils.Code500(QiYeShenQingFuWuActivity.this, response);
                            System.out.println(response + "       申请物业服务的网络请求");
                            if (response.indexOf("200") != -1) {
//                                Gson gson = new Gson();
//                                QiYeFuWuShenQingEntity qiYeFuWuShenQingEntity = gson.fromJson(response, QiYeFuWuShenQingEntity.class);
                                Toast.makeText(QiYeShenQingFuWuActivity.this, "申请成功！", Toast.LENGTH_SHORT).show();
//                                Intent intent = new Intent(QiYeShenQingFuWuActivity.this,FuWuShenQingJiLuJinXingActivity.class);
//                                intent.putExtra("entype","2");
//                                startActivity(intent);
                                finish();
                            } else if (response.indexOf("400") != -1) {
                                Gson gson = new Gson();
                                QiYeShenQingShiBaiEntity qiYeShenQingShiBaiEntity = gson.fromJson(response, QiYeShenQingShiBaiEntity.class);
                                Toast.makeText(QiYeShenQingFuWuActivity.this, qiYeShenQingShiBaiEntity.getMsg(), Toast.LENGTH_SHORT).show();
                                finish();
                            }

                        }
                    });
        } else if (yongjiu.equals("1")) {
            String s = tvStart.getText().toString().trim() + " - " + tvEnd.getText().toString().trim();
            System.out.println(s+"     ssssssssss");
            OkHttpUtils.post()
                    .url(ContractUtils.LOGIN_URL + "Life/service")
                    .addHeader("token", ContractUtils.getTOKEN(QiYeShenQingFuWuActivity.this))
                    .addParams("parkId", ContractUtils.getParkId(QiYeShenQingFuWuActivity.this))
                    .addParams("Preferences_id", fuwuid)
                    .addParams("money", etYouhuiquanJine.getText().toString().trim())
                    .addParams("nember", etNumber.getText().toString().trim())
                    .addParams("permanent", yongjiu)
                    .addParams("use_time", tvStart.getText().toString().trim() + " - " + tvEnd.getText().toString().trim())
                    .addParams("Remarks", etBeizhu.getText().toString().trim())
                    .addParams("name", etName.getText().toString().trim())
                    .addParams("phone", etPhone.getText().toString().trim())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            System.out.println(e + "    222eeeeeeeeee");
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            System.out.println(ContractUtils.getTOKEN(QiYeShenQingFuWuActivity.this) + "       token");
                            System.out.println(ContractUtils.getParkId(QiYeShenQingFuWuActivity.this) + "      parkId");
                            System.out.println(fuwuid + "        Preferences_id ");
                            System.out.println(etYouhuiquanJine.getText().toString().trim() + "          money");
                            System.out.println(etNumber.getText().toString().trim() + "            nember ");
                            System.out.println(yongjiu + "           permanent");
                            System.out.println(etBeizhu.getText().toString().trim() + "         Remarks ");
                            System.out.println(etName.getText().toString().trim() + "      name  ");
                            System.out.println(etPhone.getText().toString().trim() + "         phone");
                            System.out.println(tvStart.getText().toString().trim() + " - " + tvEnd.getText().toString().trim() + "         use_time ");


                            ContractUtils.Code500(QiYeShenQingFuWuActivity.this, response);
                            System.out.println(response + "       申请物业服务的网络请求");
                            if (response.indexOf("200") != -1) {
//                                Gson gson = new Gson();
//                                QiYeFuWuShenQingEntity qiYeFuWuShenQingEntity = gson.fromJson(response, QiYeFuWuShenQingEntity.class);
                                Toast.makeText(QiYeShenQingFuWuActivity.this, "申请成功！", Toast.LENGTH_SHORT).show();
//                                Intent intent = new Intent(QiYeShenQingFuWuActivity.this,FuWuShenQingJiLuJinXingActivity.class);
//                                intent.putExtra("entype","2");
//                                startActivity(intent);
                                finish();
                            } else if (response.indexOf("400") != -1) {
                                Gson gson = new Gson();
                                QiYeShenQingShiBaiEntity qiYeShenQingShiBaiEntity = gson.fromJson(response, QiYeShenQingShiBaiEntity.class);
                                Toast.makeText(QiYeShenQingFuWuActivity.this, qiYeShenQingShiBaiEntity.getMsg(), Toast.LENGTH_SHORT).show();
                                finish();
                            }


                        }
                    });
        }
    }


}
